// pages/order-confirm/order-confirm.js
const {
  getCustomerAddress,
  createOrder,
  getPaymentParams,
} = require("../../api/order.js");
const userStore = require("../../store/userStore.js");

Page({
  data: {
    cartItems: [], // 购物车商品
    selectedAddress: null, // 选中的地址
    addressList: [], // 地址列表
    orderRemark: "", // 订单备注（保留用于API调用）
    leaveWords: "", // 用户留言
    showLeaveWordsDrawer: false, // 是否显示留言抽屉
    orderAmount: null, // 订单金额
    canSubmit: false, // 是否可以提交
    loading: false, // 加载状态
    usePoints: true, // 是否使用积分
  },

  onLoad(options) {
    console.log("订单确认页面加载", options);
    console.log("当前用户状态", userStore.getUserInfo());
    // 获取购物车商品数据
    this.loadCartItems();
    // 加载地址列表
    this.loadAddressList();
  },

  /**
   * 加载购物车商品
   */
  loadCartItems() {
    // 从全局数据或页面参数中获取购物车商品
    const cartItems = getApp().globalData.checkoutItems || [];
    this.setData({
      cartItems: cartItems,
    });

    // 清除全局数据
    delete getApp().globalData.checkoutItems;
  },

  /**
   * 加载地址列表
   */
  async loadAddressList() {
    try {
      wx.showLoading({ title: "加载中..." });

      const response = await getCustomerAddress();

      wx.hideLoading();

      if (response.code === 0) {
        const addressList = response.data || [];
        this.setData({
          addressList: addressList,
        });

        // 选择地址
        this.selectDefaultAddress(addressList);
      } else {
        wx.showToast({
          title: response.message || "加载地址失败",
          icon: "none",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("加载地址列表失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 选择默认地址
   */
  selectDefaultAddress(addressList) {
    if (addressList.length === 0) {
      this.setData({
        selectedAddress: null,
      });
      return;
    }

    // 优先选择默认地址
    let defaultAddress = addressList.find(
      (addr) => addr.isDefault && addr.status === 1
    );

    // 如果没有默认地址，选择第一个有效地址
    if (!defaultAddress) {
      defaultAddress = addressList.find((addr) => addr.status === 1);
    }

    this.setData({
      selectedAddress: defaultAddress || null,
    });

    // 选择地址后预览订单
    if (defaultAddress) {
      this.previewOrder();
    }
  },

  /**
   * 选择地址
   */
  selectAddress() {
    wx.navigateTo({
      url: "/pages/address/address?select=true",
    });
  },

  /**
   * 添加地址
   */
  addAddress() {
    wx.navigateTo({
      url: "/pages/address-edit/address-edit",
    });
  },

  /**
   * 订单备注输入
   */
  onRemarkInput(e) {
    this.setData({
      orderRemark: e.detail.value,
    });
  },

  /**
   * 积分开关变化
   */
  onPointsSwitchChange(e) {
    const usePoints = e.detail.value;
    this.setData({
      usePoints: usePoints,
    });

    // 重新预览订单以更新金额
    this.previewOrder();
  },

  /**
   * 增加商品数量
   */
  increaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = this.data.cartItems;

    if (index >= 0 && index < cartItems.length) {
      cartItems[index].quantity += 1;

      this.setData({
        cartItems: cartItems,
      });

      // 重新预览订单以更新金额
      this.previewOrder();
    }
  },

  /**
   * 减少商品数量
   */
  decreaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = this.data.cartItems;

    if (
      index >= 0 &&
      index < cartItems.length &&
      cartItems[index].quantity > 1
    ) {
      cartItems[index].quantity -= 1;

      this.setData({
        cartItems: cartItems,
      });

      // 重新预览订单以更新金额
      this.previewOrder();
    }
  },

  /**
   * 预览订单
   */
  async previewOrder() {
    console.log("预览订单开始", {
      selectedAddress: this.data.selectedAddress,
      cartItems: this.data.cartItems,
    });

    if (!this.data.selectedAddress || this.data.cartItems.length === 0) {
      console.log("预览订单条件不满足");
      return;
    }

    try {
      this.setData({ loading: true });

      // 构建商品列表
      const items = this.data.cartItems.map((item) => ({
        spuId: item.spuId,
        skuId: item.skuId,
        quantity: item.quantity,
        unitPrice: (item.unitPrice || 0).toString(),
      }));

      const orderData = {
        orderType: 1, // 普通订单
        addressId: this.data.selectedAddress.id,
        remark: this.data.orderRemark,
        usePoints: this.data.usePoints,
        create: false, // 预览订单
        items: items,
      };

      console.log("预览订单请求数据", orderData);
      const response = await createOrder(orderData);
      console.log("预览订单响应", response);

      this.setData({ loading: false });

      if (response.code === 0) {
        console.log("预览订单成功", response.data.amountDTO);
        this.setData({
          orderAmount: response.data.amountDTO,
          canSubmit: true,
        });
      } else {
        console.error("预览订单失败", response);
        wx.showToast({
          title: response.message || "预览订单失败",
          icon: "none",
        });
      }
    } catch (error) {
      this.setData({ loading: false });
      console.error("预览订单失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 提交订单
   */
  async submitOrder() {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请完善订单信息",
        icon: "none",
      });
      return;
    }

    try {
      wx.showLoading({ title: "提交中..." });

      // 构建商品列表
      const items = this.data.cartItems.map((item) => ({
        spuId: item.spuId,
        skuId: item.skuId,
        quantity: item.quantity,
        unitPrice: (item.unitPrice || 0).toString(),
      }));

      const orderData = {
        orderType: 1, // 普通订单
        addressId: this.data.selectedAddress
          ? this.data.selectedAddress.id
          : "",
        remark: this.data.orderRemark,
        usePoints: this.data.usePoints,
        create: true, // 确认下单
        items: items,
      };

      // 创建订单
      const orderResponse = await createOrder(orderData);

      if (orderResponse.code === 0) {
        const orderInfo = orderResponse.data;

        // 获取支付参数
        wx.showLoading({ title: "获取支付参数..." });

        const paymentResponse = await getPaymentParams({
          orderId: orderInfo.orderId,
        });

        wx.hideLoading();

        if (paymentResponse.code === 0) {
          const paymentParams = paymentResponse.data.data; // 解析嵌套的data结构

          // 调用微信支付
          wx.requestPayment({
            timeStamp: paymentParams.timeStamp,
            nonceStr: paymentParams.nonceStr,
            package: paymentParams.package,
            signType: paymentParams.signType,
            paySign: paymentParams.paySign,
            success: (res) => {
              console.log("支付成功", res);
              wx.showToast({
                title: "支付成功",
                icon: "success",
              });

              // 跳转到订单详情页面
              setTimeout(() => {
                wx.navigateTo({
                  url: `/pages/order-detail/order-detail?id=${orderInfo.orderId}`,
                });
              }, 1500);
            },
            fail: (err) => {
              console.error("支付失败", err);
              if (err.errMsg.includes("cancel")) {
                wx.showToast({
                  title: "支付已取消",
                  icon: "none",
                });
              } else {
                wx.showToast({
                  title: "支付失败，请重试",
                  icon: "none",
                });
              }

              // 支付失败也跳转到订单详情页面
              setTimeout(() => {
                wx.navigateTo({
                  url: `/pages/order-detail/order-detail?id=${orderInfo.orderId}`,
                });
              }, 2000);
            },
          });
        } else {
          wx.showToast({
            title: paymentResponse.message || "获取支付参数失败",
            icon: "none",
          });

          // 获取支付参数失败，直接跳转到订单详情
          setTimeout(() => {
            wx.navigateTo({
              url: `/pages/order-detail/order-detail?id=${orderInfo.orderId}`,
            });
          }, 2000);
        }
      } else {
        wx.hideLoading();
        wx.showModal({
          title: "提交失败",
          content: orderResponse.message || "订单提交失败，请重试",
          showCancel: false,
          confirmText: "确定",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("提交订单失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 页面显示时刷新数据
   */
  onShow() {
    // 检查是否有选中的地址（从地址选择页面返回）
    const selectedAddress = getApp().globalData.selectedAddress;
    if (selectedAddress) {
      this.setData({
        selectedAddress: selectedAddress,
      });
      // 清除全局数据
      delete getApp().globalData.selectedAddress;
      // 重新预览订单
      this.previewOrder();
      return;
    }

    // 检查是否有新添加的地址（从地址编辑页面返回）
    const newAddress = getApp().globalData.newAddress;
    if (newAddress) {
      // 将新地址添加到地址列表中
      const currentAddressList = this.data.addressList;
      const updatedAddressList = [...currentAddressList, newAddress];

      this.setData({
        addressList: updatedAddressList,
        selectedAddress: newAddress, // 自动选择新添加的地址
      });

      // 清除全局数据
      delete getApp().globalData.newAddress;

      // 重新预览订单
      this.previewOrder();

      wx.showToast({
        title: "已自动选择新地址",
        icon: "success",
      });
    }
  },

  // 显示留言抽屉
  showLeaveWordsDrawer() {
    // 如果有现有留言，将其显示在输入框中
    this.setData({
      showLeaveWordsDrawer: true,
      leaveWords: this.data.orderRemark || "",
    });
  },

  // 关闭留言抽屉
  closeLeaveWordsDrawer() {
    this.setData({
      showLeaveWordsDrawer: false,
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 留言输入
  onLeaveWordsInput(e) {
    this.setData({
      leaveWords: e.detail.value,
    });
  },

  // 确认留言
  confirmLeaveWords() {
    // 将留言内容同步到订单备注，并处理文本省略
    const remark = this.data.leaveWords.trim();
    const truncatedRemark =
      remark.length > 20 ? remark.substring(0, 20) + "..." : remark;

    this.setData({
      orderRemark: remark,
      orderRemarkDisplay: truncatedRemark,
      showLeaveWordsDrawer: false,
    });

    wx.showToast({
      title: "留言已保存",
      icon: "success",
    });
  },
});
